#!/usr/bin/env python
# -*- coding: utf-8 -*-

import base64
import json
import random
import time

import matplotlib
import os
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import requests
from matplotlib.gridspec import GridSpec
import matplotlib.patches as mpatches
from jingdong_order_synchronization_kuaipu.dingding_robot.media_upload import MediaUpload
from jingdong_order_synchronization_kuaipu.dingding_robot.messages_push import MessagePush
from all_jingdong_order_datas.all_jingdong_analyze import GetOrderDatas,DetailAnalyze

# 设置显示选项以打印所有列
# pd.set_option('display.max_columns', None)  # 显示所有列
# pd.set_option('display.expand_frame_repr', False)  # 禁止换行
# pd.set_option('display.max_colwidth', None)  # 显示完整列内容（不截断）

def load_data(zi_csv_file,zi_delete_csv_file,zhu_csv_file,zhu_delete_csv_file):
    """CSV数据加载和预处理（文件不存在时返回空DataFrame）"""
    def safe_read_csv(path, date_columns):
        """安全读取CSV文件（文件不存在返回空DataFrame）"""
        try:
            return pd.read_csv(path, parse_dates=date_columns)
        except FileNotFoundError:
            return pd.DataFrame()

    def load_and_process(csv_file, delete_csv_file):
        """通用加载和处理逻辑"""
        # 加载原始数据（文件不存在时返回空DataFrame）
        df = safe_read_csv(csv_file, ['order_create_date'])
        if df.empty:  # 如果主文件不存在，直接返回空DataFrame
            return pd.DataFrame()

        df_deep = df.copy(deep=True)
        df_deep['kuaipu_ware_category_split'] = df_deep['kuaipu_ware_category'].str.split(',').str[0]

        # 加载删除订单数据（文件不存在时视为无删除订单）
        df_delete = safe_read_csv(delete_csv_file, ['order_create_date'])
        delete_ids = df_delete['jingdong_order_id'] if not df_delete.empty else []

        # 过滤需删除的订单
        return df_deep[~df_deep['jingdong_order_id'].isin(delete_ids)]

    # 加载并处理子数据和主数据
    df_zi = load_and_process(zi_csv_file, zi_delete_csv_file)
    df_zhu = load_and_process(zhu_csv_file, zhu_delete_csv_file)
    # print(df_zhu)
    combined_df = pd.concat([df_zi, df_zhu], axis=0, ignore_index=True)
    # print(combined_df)
    return combined_df  # 返回合并后的DataFrame


def daily_analysis(df, analysis_date,csv_file):
    """
    Perform daily analysis for the specified date
    """
    with open("analyze_datas/sales_target.json", "r") as f:
        sales_targets = json.load(f)
    year = analysis_date.year
    month = analysis_date.month
    kpi = sales_targets[f'{year}'][f"{month}"]["kpi"]
    # Filter data for the specific date
    df['order_create_date'] = pd.to_datetime(df['order_create_date'], errors='coerce')
    daily_df = df[df['order_create_date'].dt.date == analysis_date.date()]


    daily_result = DetailAnalyze(analysis_date).daily_analysis(csv_file)
    daily_totals = daily_result["daily_totals"]
    monthly_totals = daily_result["monthly_totals"]


    # 2. Sync status analysis
    # daily_sync_analysis = daily_df.groupby(daily_df['kuaipu_ware_code'].notna()).agg({
    #     'jingdong_order_id': 'nunique',
    #     'jingdong_ware_num': 'sum',
    #     'jingdong_procurement_total_price': 'sum'
    # }).reset_index()
    # daily_sync_analysis.columns = ['is_synced', 'order_count', 'product_count', 'total_amount']
    # daily_sync_analysis['is_synced'] = daily_sync_analysis['is_synced'].map({True: 'Synced', False: 'Not Synced'})

    # 3. Brand and Category Analysis
    daily_brand_category_analysis = daily_df.groupby(['kuaipu_ware_brand']).agg({
        'jingdong_order_id': 'nunique',
        'jingdong_ware_num': 'sum',
        'jingdong_jd_total_price':'sum',
        'jingdong_procurement_total_price': 'sum'
    }).reset_index()
    daily_brand_category_analysis['jingdong_procurement_total_price'] = daily_brand_category_analysis['jingdong_procurement_total_price'] / 1.13

    # 4. Monthly analysis for the same month
    monthly_df = df[
        (df['order_create_date'].dt.year == analysis_date.year) &
        (df['order_create_date'].dt.month == analysis_date.month)&
        (df['order_create_date'].dt.day <= analysis_date.day)
        ]

    # monthly_sync_analysis = monthly_df.groupby(daily_df['kuaipu_ware_code'].notna()).agg({
    #     'jingdong_order_id': 'nunique',
    #     'jingdong_ware_num': 'sum',
    #     'jingdong_procurement_total_price': 'sum'
    # }).reset_index()
    # monthly_sync_analysis.columns = ['is_synced', 'order_count', 'product_count', 'total_amount']
    # monthly_sync_analysis['is_synced'] = monthly_sync_analysis['is_synced'].map({True: 'Synced', False: 'Not Synced'})

    monthly_brand_category_analysis = monthly_df.groupby(['kuaipu_ware_brand']).agg({
        'jingdong_order_id': 'nunique',
        'jingdong_ware_num': 'sum',
        'jingdong_jd_total_price': 'sum',
        'jingdong_procurement_total_price': 'sum'
    }).reset_index()
    # monthly_brand_category_analysis['monthly_jingdong_jd_total_price'] = monthly_brand_category_analysis['monthly_jingdong_jd_total_price'] / 1.13
    monthly_brand_category_analysis['jingdong_procurement_total_price'] = monthly_brand_category_analysis['jingdong_procurement_total_price'] / 1.13

    daily_special_type_analysis = daily_df.groupby(['kuaipu_ware_code']).agg({
        'jingdong_order_id': 'nunique',
        'jingdong_jd_total_price': 'sum',
        'jingdong_procurement_total_price': 'sum'
    }).reset_index()
    daily_special_type_analysis['jingdong_procurement_total_price'] = daily_special_type_analysis[
                                                                          'jingdong_procurement_total_price'] / 1.13

    monthly_special_type_analysis = monthly_df.groupby(['kuaipu_ware_code']).agg({
        'jingdong_order_id': 'nunique',
        'jingdong_jd_total_price': 'sum',
        'jingdong_procurement_total_price': 'sum'
    }).reset_index()
    monthly_special_type_analysis['jingdong_procurement_total_price'] = monthly_special_type_analysis[
                                                                            'jingdong_procurement_total_price'] / 1.13


    def get_rucang(start_time,end_time):
        with open("../jingdong_order_synchronization_kuaipu_zhuzhanghao/auth/jingdong_cookies.json", "r") as f:
            cookie_data = json.load(f)
            JSESSIONID = [cookie["value"] for cookie in cookie_data if cookie["name"] == "JSESSIONID"]
            flash = [cookie["value"] for cookie in cookie_data if cookie["name"] == "flash"]
            jingdong_cookie = f"flash={random.choice(flash)};JSESSIONID={random.choice(JSESSIONID)};"
        headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "cookie": jingdong_cookie,
        }
        # print(headers)
        payload = [{
            "page": 1,
            "pageSize": 200,
            "poCreateDateEnd": end_time,
            "poCreateDateStart": start_time,
            "queryInboundType": 1,
            "source": "2",
            "sourceId": "3",
            "stateList": ["3"],
            "yn": "1"
        }]
        # print(payload)
        url = 'https://procurement.jd.com/api/procurement/poQuery/queryPurchaseOrderList'
        response = requests.post(url, headers=headers, json=payload)
        datas = response.json()["data"]["data"]
        # print(datas)
        rucang_totalPrice = 0
        for data in datas:
            rucang_totalPrice += data["totalPrice"]
        return rucang_totalPrice

    daily_start_time = f"{analysis_date.date()} 00:00:00"
    end_time = f"{analysis_date.date()} 23:59:59"
    monthly_start_time = f"{analysis_date.replace(day=1).date()} 00:00:00"

    daily_rucang_totalPrice = get_rucang(daily_start_time,end_time)
    monthly_rucang_totalPrice = get_rucang(monthly_start_time,end_time)
    daily_rucang_totalPrice = daily_rucang_totalPrice / 1.13
    monthly_rucang_totalPrice = monthly_rucang_totalPrice / 1.13
    return {
        'daily_totals': daily_totals,
        # 'daily_sync_analysis': daily_sync_analysis,
        'daily_brand_category_analysis': daily_brand_category_analysis,
        'monthly_totals': monthly_totals,
        # 'monthly_sync_analysis': monthly_sync_analysis,
        'monthly_brand_category_analysis': monthly_brand_category_analysis,
        'kpi':kpi,
        'daily_special_type': daily_special_type_analysis,
        'monthly_special_type': monthly_special_type_analysis,
        'daily_rucang_totalPrice': daily_rucang_totalPrice,
        'monthly_rucang_totalPrice': monthly_rucang_totalPrice,
    }

def photo_analysis(result,analysis_date):
    # print(result)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    matplotlib.use('TkAgg')
    # available_styles = plt.style.available
    # 打印样式表名称
    # for style in available_styles:
    #     print(style)
    # Prepare data for table
    daily_values = [
        result['daily_totals']['total_orders'],
        result['daily_totals']['total_products'],
        f"{result['daily_totals']['jingdong_jd_total_price']:,.2f}",
        f"{result['daily_totals']['total_order_amount']:,.2f}"
    ]
    print(daily_values)
    monthly_values = [
        result['monthly_totals']['total_orders'],
        result['monthly_totals']['total_products'],
        f"{result['monthly_totals']['jingdong_jd_total_price']:,.2f}",
        f"{result['monthly_totals']['total_order_amount']:,.2f}"
    ]
    print(monthly_values)

    daily_rucang_totalPrice = f"{result['daily_rucang_totalPrice']:,.2f}"
    monthly_rucang_totalPrice = f"{result['monthly_rucang_totalPrice']:,.2f}"
    # Create figure and axis
    fig = plt.figure(figsize=[16, 10])
    gs = GridSpec(8, 8)  # 明确指定高度比例
    ax1 = fig.add_subplot(gs[0:3, 0:4])
    ax2 = fig.add_subplot(gs[0:3, 4:8])
    ax3 = fig.add_subplot(gs[3:6, 0:3])
    ax4 = fig.add_subplot(gs[3:8, 3:8])
    ax1.axis('off')
    # ax2.axis('off')
    ax3.axis('off')
    ax4.axis('off')
    ax1.set_title('京东订单销售总况', fontsize=18)
    # ax2.set_title('京东订单日金额占比', fontsize=10)
    ax3.set_title('特殊型号订单销售', fontsize=18, y=0.8)
    ax4.set_title('京东订单商品类目销售总览', fontsize=18)
    # Create table
    table1_data = [
        ['维度', f'{analysis_date.strftime('%Y-%m-%d')}', f'{analysis_date.strftime('%Y-%m')}'],
        ['订单数量', daily_values[0], monthly_values[0]],
        ['商品数量', daily_values[1], monthly_values[1]],
        ['京东销售额/元', daily_values[2], monthly_values[2]],
        ['公司销售额/元', daily_values[3], monthly_values[3]],
        ['入仓金额/元',daily_rucang_totalPrice,monthly_rucang_totalPrice]
    ]
    # print(f"table1_data:{table1_data}")
    # Color palette
    header_color = '#526D82'
    row_colors = ['#F0EBE3', '#F6F5F2']
    edge_color = 'gray'

    # Create the table
    table1 = ax1.table(
        cellText=table1_data,
        loc='center',
        cellLoc='center',
        colWidths=[0.5, 0.35, 0.35],
        bbox=[0,0,1,1],
    )

    # Style the table
    table1.auto_set_font_size(False)
    table1.set_fontsize(14)
    table1.scale(1, 2)

    # Color the header
    for i in range(3):
        table1[(0, i)].set_facecolor(header_color)
        table1[(0, i)].set_text_props(color='white', fontweight='bold')

    # Alternate row colors
    for i in range(1, 5):
        for j in range(3):
            cell = table1[(i, j)]
            if i == len(table1_data) - 1:
                cell.set_fontsize(12)
                cell.get_text().set_color('red')
                cell.set_text_props(weight='bold')
                cell.set_facecolor('#AEBDCA')
                cell.set_edgecolor(edge_color)
            else:
                table1[(i, j)].set_facecolor(row_colors[i % 2])
                table1[(i, j)].set_edgecolor(edge_color)







    # 计算实际销售额和KPI目标值
    actual = round(float(result['monthly_totals']['total_order_amount'] + result['monthly_rucang_totalPrice']), 2)
    kpi_target = round(result['kpi'])


    # 根据是否超额调整数据和颜色
    if actual <= kpi_target:
        # 未超额：显示已完成和未完成
        exceeded = kpi_target - actual
        table2_data = [actual, max(exceeded, 0)]  # 确保未完成非负
        labels = ['已完成月销售额', '未完成月销售额']
        colors = ['#FADA7A', '#81BFDA']
    else:
        # 超额：显示KPI目标和超额部分
        exceeded = actual - kpi_target
        table2_data = [kpi_target, exceeded]
        labels = ['达成KPI', '超额销售额']
        colors = ['#FADA7A', '#FF9999']  # 用红色强调超额
    # 计算数据总和（用于后续百分比计算）
    total = sum(table2_data)
    # 绘制饼图
    wedges, texts, autotexts = ax2.pie(
        table2_data,
        autopct=lambda pct: f'{(pct * total / kpi_target):.1f}%',
        labels=None,
        colors=colors,
        startangle=30,
        textprops={'fontsize': 12, 'color': 'black'},
        wedgeprops={'linewidth': 1, 'edgecolor': 'white'},
        pctdistance=0.75
    )

    # 创建图例句柄
    kpi_legend = mpatches.Patch(
        color='none',  # 无颜色填充
        label=f'KPI目标值: {kpi_target:,.2f}'  # 显示KPI数值
    )

    # 调整图例位置避免重叠
    ax2.legend(
        handles=[kpi_legend],
        loc='upper left',  # 位置可调整（如 'lower right'）
        bbox_to_anchor=(0.8, 1),  # 调整图例位置
        fontsize=14,
        frameon=False  # 可选：隐藏边框
    )

    # 添加带引导线的金额标签（优化版本）
    bbox_props = dict(boxstyle="round,pad=0.3", fc="white", ec="grey", lw=0.5)
    kw = dict(
        arrowprops=dict(
            arrowstyle="-",
            color="#666666",
            connectionstyle="arc3,rad=0.1"  # 更紧凑的引导线
        ),
        bbox=bbox_props,
        zorder=10,  # 确保标签在最上层
        va="center",
        fontsize=12  # 适当缩小字体
    )

    # 修正后的标签标注逻辑
    for i, (wedge, amount, label) in enumerate(zip(wedges, table2_data, labels)):
        ang = (wedge.theta2 + wedge.theta1) / 2
        x = np.cos(np.deg2rad(ang)) * 0.8  # 从饼图边缘开始（0.8半径位置）
        y = np.sin(np.deg2rad(ang)) * 0.8
        ha = "center"
        va = "center"
        # 智能定位参数
        offset_multiplier = 45  # 使用绝对偏移量（单位：点）
        if 45 < ang <= 135:  # 顶部区域
            xytext = (0, offset_multiplier)
            va = 'bottom'
        elif 135 < ang <= 225:  # 左侧区域
            xytext = (-offset_multiplier, 0)
            ha = 'right'
        elif 225 < ang <= 315:  # 底部区域
            xytext = (0, -offset_multiplier)
            va = 'top'
        else:  # 右侧区域
            xytext = (offset_multiplier, 0)
            ha = 'left'

        # 添加标注
        ax2.annotate(
            f'{label}\n{amount:,.2f}',
            xy=(x, y),  # 修正为饼图边缘坐标
            xytext=xytext,
            textcoords='offset points',  # 确保使用点偏移坐标系
            horizontalalignment=ha,
            verticalalignment=va,
            **kw
        )


    with open("analyze_datas/sales_target.json", "r") as f:
        sales_targets = json.load(f)
    sales_targets[f'{analysis_date.year}'][f'{analysis_date.month}'].update({
        "actual": actual, "exceeded": exceeded, "kpi_ratio": round((actual / kpi_target) * 100, 2)
    })
    # 写回文件（保持格式美观）
    with open("analyze_datas/sales_target.json", "w", encoding="utf-8") as f:
        json.dump(sales_targets, f, indent=2, ensure_ascii=False)

    daily_special_type = result['daily_special_type']
    monthly_special_type = result['monthly_special_type']
    name_mapping = {
        "HP-29985": "MP2014",
        "HP-010101010301-00000006": "MP2014N",
        "HP-010102010301-00000053": "MC2000EW",
    }
    HP_codes = ['HP-29985', 'HP-010101010301-00000006', 'HP-010102010301-00000053']
    # 处理日数据和月数据，按kuaipu_ware_code分组求和
    daily_orders = daily_special_type.groupby('kuaipu_ware_code')['jingdong_order_id'].sum()
    monthly_orders = monthly_special_type.groupby('kuaipu_ware_code')['jingdong_order_id'].sum()

    # 构建结果DataFrame
    data = []
    for hp in HP_codes:
        mapped_name = name_mapping[hp]
        day_count = daily_orders.get(hp, 0)
        month_count = monthly_orders.get(hp, 0)
        data.append([mapped_name, day_count, month_count])

    df3 = pd.DataFrame(data, columns=['维度', '日订单数', '月订单数'])
    # print(data)
    # 将DataFrame转换为表格数据（包含表头）
    table3_data = [df3.columns.tolist()] + df3.values.tolist()

    # 创建表格
    table3 = ax3.table(cellText=table3_data,
                       colLabels=None,  # 因为已经包含在table_data
                       cellLoc='center',
                       loc='bottom',
                       bbox=[0, 0, 1, 0.6])  # 调整表格位置和大小
    # 设置表格样式
    table3.auto_set_font_size(False)
    table3.set_fontsize(14)
    table3.scale(1, 2)  # 调整单元格大小

    # 设置列颜色
    for (row, col), cell in table3.get_celld().items():
        if row == 0:  # 表头行
            cell.set_facecolor('#40466e')
            cell.set_text_props(color='white')
        else:  # 数据行
            cell.set_facecolor('#f1f1f1')
        cell.set_edgecolor('white')


    def process_brand_data(daily_df, monthly_df):
        merged = pd.merge(
            daily_df, monthly_df,
            on=['kuaipu_ware_brand'],
            how='outer',
            suffixes=('_daily', '_monthly')
        ).fillna(0)

        # 格式转换
        merged['jingdong_order_id_daily'] = merged['jingdong_order_id_daily'].astype(int)
        merged['jingdong_order_id_monthly'] = merged['jingdong_order_id_monthly'].astype(int)
        merged['jingdong_ware_num_daily'] = merged['jingdong_ware_num_daily'].astype(int)
        merged['jingdong_ware_num_monthly'] = merged['jingdong_ware_num_monthly'].astype(int)

        return merged[['kuaipu_ware_brand',
                       'jingdong_order_id_daily', 'jingdong_order_id_monthly',
                       'jingdong_ware_num_daily', 'jingdong_ware_num_monthly',
                       'jingdong_procurement_total_price_daily', 'jingdong_procurement_total_price_monthly']]

    brand_data = process_brand_data(result['daily_brand_category_analysis'],
                                    result['monthly_brand_category_analysis'])
    add_row = {'kuaipu_ware_brand':'总计',
                       'jingdong_order_id_daily':brand_data['jingdong_order_id_daily'].sum(), 'jingdong_order_id_monthly':brand_data['jingdong_order_id_monthly'].sum(),
                       'jingdong_ware_num_daily':brand_data['jingdong_ware_num_daily'].sum(), 'jingdong_ware_num_monthly':brand_data['jingdong_ware_num_monthly'].sum(),
                       'jingdong_procurement_total_price_daily':brand_data['jingdong_procurement_total_price_daily'].sum(), 'jingdong_procurement_total_price_monthly':brand_data['jingdong_procurement_total_price_monthly'].sum()}
    brand_data = pd.concat([brand_data, pd.DataFrame([add_row])], ignore_index=True)
    # print(type(brand_data),brand_data)
    brand_data['jingdong_procurement_total_price_daily'] = brand_data['jingdong_procurement_total_price_daily'].round().apply(lambda x: f"{x:,.2f}")
    brand_data['jingdong_procurement_total_price_monthly'] = brand_data['jingdong_procurement_total_price_monthly'].round().apply(lambda x: f"{x:,.2f}")
    brand_data['kuaipu_ware_brand'] = brand_data['kuaipu_ware_brand'].str.replace(r'[(（].*?[）)]', '',regex=True).str.strip()
    map_columns_dict = {
        'kuaipu_ware_brand':'快普品牌',
        'kuaipu_ware_category_split':'快普品类',
        'jingdong_order_id_daily':'日订单量',
        'jingdong_order_id_monthly':'月订单量',
        'jingdong_ware_num_daily':'日商品量',
        'jingdong_ware_num_monthly':'月商品量',
        'jingdong_procurement_total_price_daily':'日销售额/元',
        'jingdong_procurement_total_price_monthly':'月销售额/元'
    }
    brand_data.rename(columns=map_columns_dict,inplace=True)

    table4_data = brand_data.values
    # print(f"table3_data:{table3_data}")
    columns = brand_data.columns.tolist()
    # print(columns)
    # Create the table


    table4 = ax4.table(
        cellText=table4_data,
        colLabels=columns,
        loc='center',
        cellLoc='center',
        colWidths=[0.3, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35],
        bbox=[0, 0, 1, 1]
    )
    # Style the table
    table4.auto_set_font_size(False)
    table4.set_fontsize(12)
    table4.scale(1, 2)

    # Color the header
    table4_header_color = '#7895B2'
    table4_row_colors = ['#F0EBE3', '#F6F5F2']
    table4_edge_color = 'gray'

    for i in range(len(columns)):
        table4[(0, i)].set_facecolor(table4_header_color)
        table4[(0, i)].set_text_props(color='white', fontweight='bold')

    for i in range(1, len(brand_data) + 1):
        for j in range(len(columns)):
            table4[(i, j)].set_facecolor(table4_row_colors[i % 2])
            table4[(i, j)].set_edgecolor(table4_edge_color)
            cell = table4[(i, j)]

            # print(cell.get_text())
            if i > 0 and (j == 1 or j == 3):
                content = int(brand_data.iloc[i - 1, j])

                if content > 0:
                    cell.get_text().set_color('#CD5C08')
                    cell.set_text_props(weight='bold')
                    cell.set_facecolor('#D6EFD8')
                    cell.set_edgecolor(table4_edge_color)
            if i == len(brand_data):
                cell.set_fontsize(12)
                cell.get_text().set_color('red')
                cell.set_text_props(weight='bold')
                cell.set_facecolor('#AEBDCA')
                cell.set_edgecolor(table4_edge_color)

    # Save the figure
    plt.tight_layout(pad=3.0)
    plt.savefig('analyze_datas/jingdongorders/sales_table.png', dpi=300, bbox_inches='tight')
    plt.close()
    # plt.show()

def upload_image_to_dingtalk(image_path):

    # get_token = requests.get("https://oapi.dingtalk.com/gettoken?appkey=dingbqfumksbd4jw3gex&appsecret=zAuhVtSnv4yzXP78q3EabY7AZlTL8_9xATfRb_Jlqsw1T4HBTN6yAK9kMiVr-60-")
    # access_token = get_token.json()['access_token']
    # print(access_token)
    url = f"https://oapi.dingtalk.com/media/upload?access_token=f0966bb1887533bd818daeb050d3dfb5&type=image"
    with open(image_path, 'rb') as f:
        # print(f)
        files = {'media': f}
        response = requests.post(url, files=files)
        # print(response.json())
        return response.json()
    # if result['errcode'] == 0:
    #     return result['media_id']
    # else:
    #     raise Exception(f"Upload image failed: {result['errmsg']}")
def main():
    # Set analysis date to the previous day
    analysis_date = datetime.now() - timedelta(days=1)
    # 将字符串转换为日期对象
    date_obj = datetime.strptime(analysis_date.strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S')

    # 获取当前日期的年份和月份
    current_year = date_obj.year
    current_month = date_obj.month

    csv_file = f'../all_jingdong_order_datas/all_jingdong_order_datas/京东订单-{current_year}/京东订单-{current_year}-{current_month}.csv'

    directory = f'analyze_datas/jingdongorders/广州子公司-{current_year}'
    zi_csv_file = f'analyze_datas/jingdongorders/广州子公司-{current_year}/广州子公司-{current_year}-{current_month}.csv'
    zi_delete_csv_file = f'analyze_datas/jingdongorders/广州子公司-{current_year}/广州子公司-{current_year}-{current_month}-delete.csv'


    zhu_csv_file = f'../jingdong_order_synchronization_kuaipu_zhuzhanghao/analyze_datas/jingdongorders/广州总公司-{current_year}/广州总公司-{current_year}-{current_month}.csv'
    zhu_delete_csv_file = f'../jingdong_order_synchronization_kuaipu_zhuzhanghao/analyze_datas/jingdongorders/广州总公司-{current_year}/广州总公司-{current_year}-{current_month}-delete.csv'
    # Load the CSV file
    df = load_data(zi_csv_file,zi_delete_csv_file,zhu_csv_file,zhu_delete_csv_file)
    # Perform analysis
    results = daily_analysis(df, analysis_date,csv_file)
    photo_analysis(results,analysis_date)

    photo_path = "analyze_datas/jingdongorders/sales_table.png"

    media_id = MediaUpload().upload_media_to_dingtalk(photo_path)
    # print(media_id)

    MessagePush(media_id).image_push()

# if __name__ == "__main__":
#     main()

